package cn.com.surker.workcon.service.zhonglian;

import cn.com.surker.base.system.entity.SysLine;
import cn.com.surker.production.entity.vo.ProductionIndentVo;
import cn.com.surker.util.RandomUtils;
import cn.com.surker.util.StringUtils;
import cn.com.surker.workcon.common.GKJDBCService;
import cn.com.surker.workcon.common.RecipeTranEntity;
import cn.com.surker.workcon.service.RecipeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 工控上传配比接口 Mapper 接口
 * </p>
 *
 * @author admin
 * @since 2024-09-26
 */
@Slf4j
public class RecipeServiceImpl extends GKJDBCService implements RecipeService {

	@Override
	public Long uploadExpend(SysLine line, ProductionIndentVo indent, String code, String betLev, String filter, String freeze, String season,
							 Integer mixLast, String scale, String exper, String assoss, List<RecipeTranEntity> list, Date nowDate) {
		if (line == null || indent == null || list == null || list.isEmpty()) {
			return -1l;
		}
		Long lineId = line.getId();
		//	获取连接
		JdbcTemplate lineJdbcTemp = getLineJdbcTemp(line);
		//	任务单编号
		String indentCode = indent.getCode();
		//	根据任务单编号,查询是否存在上传数据
		String queryOldTask = "select id from PTaskList where PTaskListNo = '" + indentCode + "'";
		//	查询数据
		List<Map<String, Object>> oldTasks = lineJdbcTemp.queryForList(queryOldTask);
		if (oldTasks == null || oldTasks.isEmpty() || oldTasks.get(0) == null) {
			//	没有上传数据
			log.info("任务单{}没有查询到工控数据", indentCode);
			return -1l;
		}
		Object pTaskListID = oldTasks.get(0).get("id");
		//	查询是否存在关联数据
		//	生产线ID
		String productLineID = StringUtils.toFixedLengthString(lineId, 8);
		//	查询最最新的一条关联配合比数据
		String queryPhbSql = "select FormulaConID,FormulaMorID from PTaskFormula where PTaskListID = ? order by CreateTime desc";
		Object[] phbParam = {pTaskListID};
		List<Map<String, Object>> phbList = lineJdbcTemp.queryForList(queryPhbSql, phbParam);
		//	开启事务
		beginTransaction(lineId);
		if (phbList == null || phbList.isEmpty() || phbList.get(0) == null) {
			//	没有数据,新增
			Long aLong = addPhb(productLineID, lineId, lineJdbcTemp, indent, code, betLev, mixLast, list, nowDate, pTaskListID);
			return aLong;
		} else {
			//	存在数据,用旧数据
			return updatePhb(list, nowDate, lineId, lineJdbcTemp, productLineID, phbList);
		}

	}

	/**
	 * 更新配合比
	 *
	 * @param list
	 * @param nowDate
	 * @param lineId
	 * @param lineJdbcTemp
	 * @param productLineID
	 * @param phbList
	 * @return
	 */
	private Long updatePhb(List<RecipeTranEntity> list, Date nowDate, Long lineId, JdbcTemplate lineJdbcTemp, String productLineID, List<Map<String, Object>> phbList) {
		//	分别取出砼,砂浆的配合比
		Map<String, Object> taskFormulaMap = phbList.get(0);
		//	配合比数据
		Object formulaConID = taskFormulaMap.get("FormulaConID");
		Object formulaMorID = taskFormulaMap.get("FormulaMorID");
		//	删除子表的数据
		String deleteItemSql = "delete from FormulaReferenceItems where FormulaReferenceID in (?,?)";
		Object[] param = {formulaConID, formulaMorID};
		lineJdbcTemp.update(deleteItemSql, param);
		//	=======================创建子表数据=======================
		String insertSlaveSql = "insert into FormulaReferenceItems (FormulaReferenceID,SiloID,StuffID,TypeAmount,Status,Version,CreateTime) values (?,?,?,?,0,1,?)";
		//	子表参数
		List<Object[]> slaveParamTs = new ArrayList<>();
		List<Object[]> slaveParamRs = new ArrayList<>();
		String queryCS = "SELECT a.ID,a.stuffid FROM Silo a \n" +
			"  left join SiloProductLine b ON a.id = b.SiloID\n" +
			"  where a.SiloName = ? and b.ProductLineID = '" + productLineID + "'";
		for (int i = 0, s = list.size(); i < s; i++) {
			RecipeTranEntity recipeTranEntity = list.get(i);
			//	查询工控的仓位id
			String controlStorage = recipeTranEntity.getControlStorage();
			controlStorage = "1#水泥仓";
			Object[] csp = {controlStorage};
			List<Map<String, Object>> conResList = lineJdbcTemp.queryForList(queryCS, csp);
			if (conResList == null || conResList.isEmpty()) {
				log.info("没有查询到工控机的仓位id-1,erp传入的工控机仓位名称:{},工控机生产线id:{},erp生产线id:{}", controlStorage, productLineID, lineId);
				return -1l;
			}
			Map<String, Object> conRes = conResList.get(0);
			if (conRes == null) {
				log.info("没有查询到工控机的仓位id-2,erp传入的工控机仓位名称:{},工控机生产线id:{},erp生产线id:{}", controlStorage, productLineID, lineId);
				return -1l;
			}
			//	取出仓位id和材料id
			Object SiloID = conRes.get("ID");
			Object StuffID = conRes.get("stuffid");
			//	砼用量
			Double concreteDosage = recipeTranEntity.getConcreteDosage();
			//	砂浆用量
			Double standDosage = recipeTranEntity.getStandDosage();
			//	砼参数
			Object[] slaveParamT = {formulaConID, SiloID, StuffID, concreteDosage, nowDate};
			//	砂浆参数
			Object[] slaveParamR = {formulaMorID, SiloID, StuffID, standDosage, nowDate};
			//	添加到参数列表
			slaveParamTs.add(slaveParamT);
			slaveParamRs.add(slaveParamR);
		}
		//	插入子表数据
		lineJdbcTemp.batchUpdate(insertSlaveSql, slaveParamTs);
		lineJdbcTemp.batchUpdate(insertSlaveSql, slaveParamRs);
		return 1l;
	}

	/**
	 * 新增配合比
	 *
	 * @param productLineID
	 * @param lineId
	 * @param lineJdbcTemp
	 * @param indent
	 * @param code
	 * @param betLev
	 * @param mixLast
	 * @param list
	 * @param nowDate
	 * @param pTaskListID
	 * @return
	 */
	private Long addPhb(String productLineID, Long lineId, JdbcTemplate lineJdbcTemp, ProductionIndentVo indent, String code, String betLev, Integer mixLast, List<RecipeTranEntity> list, Date nowDate, Object pTaskListID) {
		//	=======================创建主表sql=======================
		String insertMasterSql = "insert into FormulaReference (id,FormulaMsgNo,ProductLineID,FormulaName,ConcreteStrength,PouringMode,Sink,Ftype,MixingTime,Volume,Version,Status,CreateTime) " +
			"values (?,?,?,?,?,?,?,1,?,?,1,0,?)";
		//	拼接参数
		//	砼配合比编号
		String FormulaMsgNoT = code;
		//	砂浆配合比编号
		String FormulaMsgNoR = "R" + code;
		//	强度等级
		String ConcreteStrength = betLev;
		//	浇筑方式
		String PouringMode = indent.getCastModelName();
		//	坍落度
		String Sink = indent.getSlumps();
		//	搅拌时间
		int MixingTime = mixLast;
		//	容重
		Double Volume = 1d;
		//	砼参数
		//	砼配合比id
		String mptId = RandomUtils.generateUpperString(32);
		Object[] masterParamsT = {mptId, FormulaMsgNoT, productLineID, FormulaMsgNoT, ConcreteStrength, PouringMode, Sink, MixingTime, Volume, nowDate};
		//	砂浆参数
		//	砂浆配合比id
		String mprId = RandomUtils.generateUpperString(32);
		Object[] masterParamsR = {mprId, FormulaMsgNoR, productLineID, FormulaMsgNoR, ConcreteStrength, PouringMode, Sink, MixingTime, Volume, nowDate};
		//	插入砼数据
		lineJdbcTemp.update(insertMasterSql, masterParamsT);
		//	查询砂浆数据
		lineJdbcTemp.update(insertMasterSql, masterParamsR);
		//	=======================创建子表=======================
		String insertSlaveSql = "insert into FormulaReferenceItems (FormulaReferenceID,SiloID,StuffID,TypeAmount,Status,Version,CreateTime) values (?,?,?,?,0,1,?)";
		//	子表参数
		List<Object[]> slaveParamTs = new ArrayList<>();
		List<Object[]> slaveParamRs = new ArrayList<>();
		String queryCS = "SELECT a.ID,a.stuffid FROM Silo a \n" +
			"  left join SiloProductLine b ON a.id = b.SiloID\n" +
			"  where a.SiloName = ? and b.ProductLineID = '" + productLineID + "'";
		for (int i = 0, s = list.size(); i < s; i++) {
			RecipeTranEntity recipeTranEntity = list.get(i);
			//	查询工控的仓位id
			String controlStorage = recipeTranEntity.getControlStorage();
			controlStorage = "1#水泥仓";
			Object[] csp = {controlStorage};
			List<Map<String, Object>> conResList = lineJdbcTemp.queryForList(queryCS, csp);
			if (conResList == null || conResList.isEmpty()) {
				log.info("没有查询到工控机的仓位id-1,erp传入的工控机仓位名称:{},工控机生产线id:{},erp生产线id:{}", controlStorage, productLineID, lineId);
				return -1l;
			}
			Map<String, Object> conRes = conResList.get(0);
			if (conRes == null) {
				log.info("没有查询到工控机的仓位id-2,erp传入的工控机仓位名称:{},工控机生产线id:{},erp生产线id:{}", controlStorage, productLineID, lineId);
				return -1l;
			}
			//	取出仓位id和材料id
			Object SiloID = conRes.get("ID");
			Object StuffID = conRes.get("stuffid");
			//	砼用量
			Double concreteDosage = recipeTranEntity.getConcreteDosage();
			//	砂浆用量
			Double standDosage = recipeTranEntity.getStandDosage();
			//	砼参数
			Object[] slaveParamT = {mptId, SiloID, StuffID, concreteDosage, nowDate};
			//	砂浆参数
			Object[] slaveParamR = {mprId, SiloID, StuffID, standDosage, nowDate};
			//	添加到参数列表
			slaveParamTs.add(slaveParamT);
			slaveParamRs.add(slaveParamR);
		}
		//	插入子表数据
		lineJdbcTemp.batchUpdate(insertSlaveSql, slaveParamTs);
		lineJdbcTemp.batchUpdate(insertSlaveSql, slaveParamRs);
		//	======================= 插入关联表数据 =======================
		String insertLinkSql = "insert into PTaskFormula (PTaskListID,ProductLineID,FormulaConID,FormulaMorID,Version,CreateTime,UpdateTime,Status) values (?,?,?,?,1,?,?,0)";
		//	拼接参数
		Object[] linkParam = {pTaskListID, productLineID, mptId, mprId, nowDate, nowDate};
		//	插入数据
		int update = lineJdbcTemp.update(insertLinkSql, linkParam);
		if (update > 0) {
			return 1l;
		} else {
			return -1l;
		}
	}

}
